package com.zzx.wsbehind.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2022/12/12 21:25
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/{topic}") //暴露的ws应用的路径
public class WebSocket
{
    private Session session;
    private String topic;

    private static CopyOnWriteArrayList<WebSocket> webSocketSet = new CopyOnWriteArrayList<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("topic") String topic)
    {
        this.session = session;
        this.topic=topic;
        webSocketSet.add(this);
        log.info("[websocket消息提示] 有新的连接，总数为{}",webSocketSet.size());
    }

    @OnClose
    public void onClose()
    {
        webSocketSet.remove(this);
        log.info("[websocket消息提示] 连接断开，总数为{}",webSocketSet.size());
    }

    /**
     * 处理来自客户端的消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message)
    {
        log.info("[websocket消息提示] 收到来自客户端的消息：{}",message);
        // 这里可以对接受的数据进行处理
    }

    /**
     * 向客户端发送信息（群发广播）
     * @param message
     */
    public void sendMessage(String message)
    {
        log.info("[websocket消息提示] 广播消息，message：{}",message);
        for(WebSocket webSocket:webSocketSet)
        {
            try
            {
                webSocket.session.getBasicRemote().sendText(message);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给订阅了特定主题的客户端发送消息
     * @param message
     * @param topic
     */
    public void sendMessageByTopic(String message,String topic)
    {
        log.info("[websocket消息提示] 给主题为"+topic+"发送消息，message：{}",message);
        for(WebSocket webSocket:webSocketSet)
        {
            try
            {
                if(topic.equals(webSocket.topic))
                {
                    webSocket.session.getBasicRemote().sendText(message);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

}
